package com.uduemc.biso.node.module.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.module.service.SPageService;

@RestController
@RequestMapping("/s-page")
public class SPageController {

	private static final Logger logger = LoggerFactory.getLogger(SPageController.class);

	@Autowired
	private SPageService sPageServiceImpl;

	@PostMapping("/insert")
	public RestResult insert(@Valid @RequestBody SPage sPage, BindingResult errors) {
		logger.info("insert: " + sPage.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}
		SPage data = sPageServiceImpl.insert(sPage);
		return RestResult.ok(data, SPage.class.toString());
	}

	@PutMapping("/update-by-id")
	public RestResult updateById(@Valid @RequestBody SPage sPage, BindingResult errors) {
		logger.info("updateById: " + sPage.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}
		SPage findOne = sPageServiceImpl.findOne(sPage.getId());
		if (findOne == null) {
			return RestResult.noData();
		}
		SPage data = sPageServiceImpl.updateById(sPage);
		return RestResult.ok(data, SPage.class.toString());
	}

	@GetMapping("/find-one/{id:\\d+}")
	public RestResult findOne(@PathVariable("id") Long id) {
		SPage data = sPageServiceImpl.findOne(id);
		if (data == null) {
			return RestResult.noData();
		}
		return RestResult.ok(data, SPage.class.toString());
	}

	@GetMapping(value = { "/find-all" })
	public RestResult findAll(@PageableDefault(page = 0, size = 12) Pageable pageable) {
		logger.info("pageable: " + pageable.toString());
		List<SPage> findAll = sPageServiceImpl.findAll(pageable);
		return RestResult.ok(findAll, SPage.class.toString(), true);
	}

	@GetMapping("/delete-by-id/{id:\\d+}")
	public RestResult deleteById(@PathVariable("id") Long id) {
		SPage findOne = sPageServiceImpl.findOne(id);
		if (findOne == null) {
			return RestResult.ok();
		}
		sPageServiceImpl.deleteById(id);
		return RestResult.ok(findOne);
	}

	@GetMapping("/find-by-host-site-id/{hostId:\\d+}/{siteId:\\d+}")
	public RestResult findByHostSiteId(@PathVariable("hostId") long hostId, @PathVariable("siteId") long siteId) {
		if (hostId < 1 || siteId < 0) {
			return RestResult.error();
		}
		List<SPage> list = sPageServiceImpl.findSPageByHostSiteId(hostId, siteId);
		if (CollectionUtils.isEmpty(list)) {
			return RestResult.noData();
		}
		return RestResult.ok(list, SPage.class.toString(), true);
	}

	/**
	 * 找出显示的page数据，status 不进行过滤!
	 * 
	 * @param hostId
	 * @param siteId
	 * @param orderBy
	 * @return
	 */
	@PostMapping("/find-by-host-site-id-and-order-by")
	public RestResult findByHostSiteIdAndOrderBy(@RequestParam("hostId") long hostId, @RequestParam("siteId") long siteId,
			@RequestParam("orderBy") String orderBy) {
		if (hostId < 1 || siteId < 0) {
			return RestResult.error();
		}
		List<SPage> list = sPageServiceImpl.findSPageByHostSiteId(hostId, siteId, orderBy);
		if (CollectionUtils.isEmpty(list)) {
			return RestResult.noData();
		}
		return RestResult.ok(list, SPage.class.toString(), true);
	}

	/**
	 * 找出显示的page数据，也就是 status 为1，hide 为0的数据
	 * 
	 * @param hostId
	 * @param siteId
	 * @param orderBy
	 * @return
	 */
	@PostMapping("/find-show-by-host-site-id-and-order-by")
	public RestResult findShowByHostSiteIdAndOrderBy(@RequestParam("hostId") long hostId, @RequestParam("siteId") long siteId,
			@RequestParam("orderBy") String orderBy) {
		if (hostId < 1 || siteId < 0) {
			return RestResult.error();
		}
		List<SPage> list = sPageServiceImpl.findSPageShowByHostSiteId(hostId, siteId, orderBy);
		if (CollectionUtils.isEmpty(list)) {
			return RestResult.noData();
		}
		return RestResult.ok(list, SPage.class.toString(), true);
	}

	/**
	 * 通过 sPage 中的 parent_id 获取该级别下的最大 order_num 然后加1写入到 sPage 数据中并且插入数据
	 * 
	 * @param sPage
	 * @param errors
	 * @return
	 */
	@PostMapping("/insert-append-order-num")
	public RestResult insertAppendOrderNum(@Valid @RequestBody SPage sPage, BindingResult errors) {
		logger.info("insert: " + sPage.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}
		SPage data = sPageServiceImpl.insertAppendOrderNum(sPage);
		return RestResult.ok(data, SPage.class.toString());
	}

	/**
	 * 批量修改
	 */
	@PutMapping("/update-list")
	public RestResult updateList(@Valid @RequestBody List<SPage> sPageList, BindingResult errors) {
		logger.info("updateList: " + sPageList.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}
		if (CollectionUtils.isEmpty(sPageList)) {
			return RestResult.noData();
		}
		return RestResult.ok(sPageServiceImpl.updateList(sPageList), SPage.class.toString(), true);
	}

	/**
	 * 通过 hostId siteId 查找匹配 rewrite 的数据
	 * 
	 * @param hostId
	 * @param siteId
	 * @param rewrite
	 * @return
	 */
	@PostMapping("/find-by-host-site-id-and-rewrite")
	public RestResult findByHostSiteIdAndRewrite(@RequestParam("hostId") long hostId, @RequestParam("siteId") long siteId,
			@RequestParam("rewrite") String rewrite) {
		if (!StringUtils.hasText(rewrite)) {
			Map<String, Object> message = new HashMap<>();
			message.put("rewrite", "不能为空");
			return RestResult.error(message);
		}
		SPage sPage = sPageServiceImpl.findByHostSiteIdAndRewrite(hostId, siteId, rewrite);
		if (sPage == null || sPage.getId().longValue() < 1) {
			return RestResult.noData();
		}
		return RestResult.ok(sPage, SPage.class.toString());
	}

	/**
	 * 通过 id hostId 获取数据
	 */
	@GetMapping("/find-by-id-host-id/{id:\\d+}/{hostId:\\d+}")
	public RestResult findByIdHostId(@PathVariable("id") long id, @PathVariable("hostId") long hostId) {
		if (id < 1 || hostId < 1) {
			return RestResult.error();
		}
		SPage sPage = sPageServiceImpl.findSPageByIdHostId(id, hostId);
		if (sPage == null || sPage.getId().longValue() < 1) {
			return RestResult.noData();
		}
		return RestResult.ok(sPage, SPage.class.toString());
	}

	/**
	 * 通过 id hostId siteId 获取数据
	 */
	@GetMapping("/find-by-id-host-site-id/{id:\\d+}/{hostId:\\d+}/{siteId:\\d+}")
	public RestResult findByIdHostSiteId(@PathVariable("id") long id, @PathVariable("hostId") long hostId, @PathVariable("siteId") long siteId) {
		if (id < 1 || hostId < 1 || siteId < 0) {
			return RestResult.error();
		}
		SPage sPage = sPageServiceImpl.findSPageByIdHostSiteId(id, hostId, siteId);
		if (sPage == null || sPage.getId().longValue() < 1) {
			return RestResult.noData();
		}
		return RestResult.ok(sPage, SPage.class.toString());
	}

	/**
	 * 通过 hostId 获取页面总数
	 */
	@GetMapping("/total-by-host-id/{hostId:\\d+}")
	public RestResult totalByHostId(@PathVariable("hostId") long hostId) {
		if (hostId < 1) {
			return RestResult.error();
		}
		int totalByHostId = sPageServiceImpl.totalByHostId(hostId);
		return RestResult.ok(totalByHostId, Integer.class.toString());
	}

	/**
	 * 通过 hostId 获取页面总数，不包含引导页
	 */
	@GetMapping("/total-by-host-id-nobootpage/{hostId:\\d+}")
	public RestResult totalByHostIdNobootpage(@PathVariable("hostId") long hostId) {
		if (hostId < 1) {
			return RestResult.error();
		}
		int totalByHostId = sPageServiceImpl.totalByHostIdNobootpage(hostId);
		return RestResult.ok(totalByHostId, Integer.class.toString());
	}

	/**
	 * 通过 hostId、siteId 获取页面总数，不包含引导页
	 */
	@GetMapping("/total-by-host-site-id-nobootpage/{hostId:\\d+}/{siteId:\\d+}")
	public RestResult totalByHostSiteIdNobootpage(@PathVariable("hostId") long hostId, @PathVariable("siteId") long siteId) {
		if (hostId < 1 || siteId < 1) {
			return RestResult.error();
		}
		int totalByHostId = sPageServiceImpl.totalByHostSiteIdNobootpage(hostId, siteId);
		return RestResult.ok(totalByHostId, Integer.class.toString());
	}

	/**
	 * 通过 parent hostId siteId 获取数据
	 */
	@GetMapping("/find-by-parent-host-site-id/{parent:\\d+}/{hostId:\\d+}/{siteId:\\d+}")
	public RestResult findByParentHostSiteId(@PathVariable("parent") long parent, @PathVariable("hostId") long hostId, @PathVariable("siteId") long siteId) {
		if (parent < 0 || hostId < 1 || siteId < 0) {
			return RestResult.error();
		}
		List<SPage> list = sPageServiceImpl.findByParentHostSiteId(parent, hostId, siteId);
		return RestResult.ok(list, SPage.class.toString(), true);
	}

	/**
	 * 通过 parent hostId 获取数据
	 */
	@GetMapping("/find-by-parent-host-id/{parent:\\d+}/{hostId:\\d+}")
	public RestResult findByParentHostId(@PathVariable("parent") long parent, @PathVariable("hostId") long hostId) {
		if (parent < 0 || hostId < 1) {
			return RestResult.error();
		}
		List<SPage> list = sPageServiceImpl.findByParentHostSiteId(parent, hostId);
		return RestResult.ok(list, SPage.class.toString(), true);
	}

	/**
	 * 通过 parent 获取数量
	 */
	@GetMapping("/total-by-parent-id/{parent:\\d+}")
	public RestResult totalByParentId(@PathVariable("parent") long parent) {
		if (parent < 0) {
			return RestResult.error();
		}
		int totalByParentId = sPageServiceImpl.totalByParentId(parent);
		return RestResult.ok(totalByParentId, Integer.class.toString());
	}

	/**
	 * 通过 systemId 获取数据
	 */
	@GetMapping("/find-by-system-id/{systemId:\\d+}")
	public RestResult findBySystemId(@PathVariable("systemId") long systemId) {
		if (systemId < 0) {
			return RestResult.error();
		}
		List<SPage> list = sPageServiceImpl.findBySystemId(systemId);
		return RestResult.ok(list, SPage.class.toString(), true);
	}

	/**
	 * 通过 hostId, systemId 获取数据
	 */
	@GetMapping("/find-by-host-system-id/{hostId:\\d+}/{systemId:\\d+}")
	public RestResult findByHostSystemId(@PathVariable("hostId") long hostId, @PathVariable("systemId") long systemId) {
		if (systemId < 0 || hostId < 1) {
			return RestResult.error();
		}
		List<SPage> list = sPageServiceImpl.findByHostSystemId(hostId, systemId);
		return RestResult.ok(list, SPage.class.toString(), true);
	}

	/**
	 * 通过 hostId, siteId, systemId 获取数据
	 */
	@GetMapping("/find-by-host-site-system-id/{hostId:\\d+}/{siteId:\\d+}/{systemId:\\d+}")
	public RestResult findByHostSiteSystemId(@PathVariable("hostId") long hostId, @PathVariable("siteId") long siteId,
			@PathVariable("systemId") long systemId) {
		if (systemId < 0 || hostId < 1 || siteId < 1) {
			return RestResult.error();
		}
		List<SPage> list = sPageServiceImpl.findByHostSiteSystemId(hostId, siteId, systemId);
		return RestResult.ok(list, SPage.class.toString(), true);
	}

	/**
	 * 通过 hostId, siteId, systemId, orderBy 获取数据
	 */
	@PostMapping("/find-by-host-site-system-id-order-by")
	public RestResult findByHostSiteSystemIdOrderBy(@RequestParam("hostId") long hostId, @RequestParam("siteId") long siteId,
			@RequestParam("systemId") long systemId, @RequestParam("orderBy") String orderBy) {
		if (systemId < 0 || hostId < 1 || siteId < 1 || StringUtils.isEmpty(orderBy)) {
			return RestResult.error();
		}
		List<SPage> list = sPageServiceImpl.findByHostSiteSystemIdOrderBy(hostId, siteId, systemId, orderBy);
		return RestResult.ok(list, SPage.class.toString(), true);
	}

}
